/*
 * The contents of this web application are subject to the Mozilla Public License Version 
 * 1.1 (the "License"); you may not use this web application except in compliance with 
 * the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
 * for the specific language governing rights and limitations under the License.
 * 
 * The Original Code is owned by and the Initial Developer of the Original Code is 
 * Composite A/S (Danish business reg.no. 21744409). All Rights Reserved
 * 
 * Section 11 of the License is EXPRESSLY amended to include a provision stating 
 * that any dispute, including but not limited to disputes related to the enforcement 
 * of the License, to which Composite A/S as owner of the Original Code, as Initial 
 * Developer or in any other role, becomes a part to shall be governed by Danish law 
 * and be initiated before the Copenhagen City Court ("K�benhavns Byret")            
 */

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Hosting;
using Composite.Core.IO;

namespace Composite.Web.Css.Less
{
    public static class CompressFiles
    {
        private static readonly string LessCompilerFilePath = HostingEnvironment.MapPath("~/Frontend/Composite/Web/Css/Less/lessc.cmd");

        public static void CompressLess(string lessFilePath, string cssFilePath, DateTime folderLastUpdatedUtc)
        {
            var scriptProc = InitProcess(lessFilePath);
            string output = GetOutput(scriptProc);

            C1File.WriteAllText(cssFilePath, output);

            File.SetLastWriteTimeUtc(cssFilePath, folderLastUpdatedUtc);
        }

        /// <summary>
        /// </summary>
        /// <param name="virtualLessFilePath">virtual path to the LESS file</param>
        /// <returns> virtual path to the compressed CSS file</returns>
        public static string CompressLess(string virtualLessFilePath)
        {
            var absouteLessFilePath = HttpContext.Current.Server.MapPath(virtualLessFilePath);
            var scriptProc = InitProcess(absouteLessFilePath);

            string output = GetOutput(scriptProc);

            var filePathCss = absouteLessFilePath.Substring(0, absouteLessFilePath.Length - ".less".Length) + ".min.css";
            C1File.WriteAllText(filePathCss, output);

            return virtualLessFilePath.Substring(0, virtualLessFilePath.Length - ".less".Length) + ".min.css";
        }

        private static string GetOutput(Process process)
        {
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            if (process.ExitCode == 2)
            {
                throw new CssCompileException(error);
            }

            if (process.ExitCode != 0)
            {
                throw new InvalidOperationException("Compiling less caused a scripting host error. " + error);
            }

            return output;
        }

        private static Process InitProcess(string filePath)
        {
            return new Process
            {
                StartInfo =
                {
                    FileName = "\"" + LessCompilerFilePath + "\"",
                    Arguments = filePath,
                    WorkingDirectory = Path.GetDirectoryName(filePath),
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                }
            };
        }


    }
}
